<template>
  <div>
    <el-collapse>
      <el-collapse-item title="商品管理介绍" name="4">
        <div>
          商品管理模块可以对客户端的商品进行增删改查等相关操作,来控制客户端商品的列表展示和商品详情
        </div>
      </el-collapse-item>
    </el-collapse>
    <el-card class="card">
      <div>
        <el-collapse>
          <el-collapse-item title="条件查询" name="4">
            <div>
              <el-row :gutter="20">
                <el-form ref="form" :model="searchForm" size="mini">
                  <el-col :span="4" :offset="0">
                    <el-form-item>
                      <el-input
                        v-model="searchForm.name"
                        placeholder="商品名称/模糊查询"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4" :offset="0">
                    <el-form-item>
                      <el-input
                        v-model="searchForm.productCategoryId"
                        placeholder="商品货号"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item label="">
                      <el-select
                        v-model="searchForm.brandName"
                        placeholder="品牌"
                        clearable
                      >
                        <el-option
                          v-for="item in options"
                          :key="item.id"
                          :label="item.name"
                          :value="item.name"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item label="">
                      <el-select
                        v-model="searchForm.publishStatus"
                        placeholder="上架状态"
                        clearable
                      >
                        <el-option label="未上架" value="0"> </el-option>
                        <el-option label="已上架" value="1"> </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item label="">
                      <el-select
                        v-model="searchForm.verifyStatus"
                        placeholder="审核状态"
                        clearable
                      >
                        <el-option label="未审核" value="0"> </el-option>
                        <el-option label="已审核" value="1"> </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4" :offset="0">
                    <el-form-item>
                      <el-button type="primary" size="mini" @click="onsubmit"
                        >查询</el-button
                      >
                      <el-button type="primary" @click="regist">重置</el-button>
                    </el-form-item>
                  </el-col>
                </el-form>
              </el-row>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>
    <el-card class="card">
      <div slot="header">
        <el-button type="primary" size="mini" @click="addProduct"
          >新增</el-button
        >
        <el-button type="primary" size="mini" @click="handeleExcel">导出商品列表excel文件</el-button>
      </div>
      <div>
        <el-table :data="productList" border style="width: 100%">
          <el-table-column fixed type="index" label="序号"> </el-table-column>
          <el-table-column label="商品图片" width="120">
            <template slot-scope="scope">
              <div>
                <img :src="scope.row.pic" alt="" class="pic" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称"> </el-table-column>
          <el-table-column prop="price" label="商品价格" width="120">
          </el-table-column>
          <el-table-column prop="productCategoryName" label="商品类别">
          </el-table-column>
          <el-table-column label="标签" width="120">
            <template slot-scope="scope">
              <p>
                最新:
                <el-switch
                  v-model="scope.row.newStatus"
                  size="small"
                  :active-value="1"
                  :inactive-value="0"
                  @change="changeStatus('newStatus', scope.row)"
                />
              </p>
              <p>
                推荐:
                <el-switch
                  v-model="scope.row.recommendStatus"
                  size="small"
                  :active-value="1"
                  :inactive-value="0"
                  @change="changeStatus('recommendStatus', scope.row)"
                />
              </p>
            </template>
          </el-table-column>
          <el-table-column label="标签2" width="120">
            <template slot-scope="scope">
              <p>
                发布:
                <el-switch
                  v-model="scope.row.publishStatus"
                  size="small"
                  :active-value="1"
                  :inactive-value="0"
                  @change="changeStatus('publishStatus', scope.row)"
                />
              </p>
              <p>
                审核:
                <el-switch
                  v-model="scope.row.verifyStatus"
                  size="small"
                  :active-value="1"
                  :inactive-value="0"
                  @change="changeStatus('verifyStatus', scope.row)"
                />
              </p>
            </template>
          </el-table-column>
          <el-table-column label="sku" width="120">
            <template slot-scope="scope">
              <div>
                <el-button type="text" @click="editSku(scope.row)"
                  >编辑sku</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量" width="120">
          </el-table-column>
          <el-table-column
            align="center"
            prop="sort"
            label="排序"
            width="150"
          />
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button @click="edit(scope.row)" type="text" size="small"
                >编辑</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="delProduct(scope.row)"
                style="color: red"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="page.pageSizes"
        :page-size="page.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog title="sku列表" :visible.sync="open">
      <el-button
        style="margin-bottom: 20px"
        type="primary"
        size="default"
        @click="addSku"
        class="btn"
        >新增</el-button
      >
      <el-table size="mini" :data="skuList" border stripe>
        <el-table-column type="index" label="#" fixed="left" />

        <el-table-column label="图片" :width="120">
          <template slot-scope="scope">
            <el-upload
              style="width: 100px; height: 100px"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="addTiImg"
              @click.native="saveSku(scope.row)"
            >
              <img
                v-if="scope.row.pic"
                style="width: 100px; height: 100px"
                :src="scope.row.pic"
                class="avatar"
              />
              <i
                v-else
                style="width: 100px; height: 100px; margin-top: -31px"
                class="el-icon-plus avatar-uploader-icon"
              />
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column label="颜色" :width="160">
          <template slot-scope="scope">
            <el-input v-model="scope.row.spData[0].value" size="mini" />
          </template>
        </el-table-column>
        <el-table-column label="大小" :width="160">
          <template slot-scope="scope">
            <el-input
              v-if="scope.row.spData[1]"
              v-model="scope.row.spData[1].value"
              size="mini"
            />
          </template>
        </el-table-column>
        <el-table-column label="库存" :width="200">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.stock"
              size="mini"
              placeholder="自定义库存"
            />
          </template>
        </el-table-column>
        <el-table-column label="预警库存" :width="200">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.lowStock"
              size="mini"
              placeholder="预警库存"
            />
          </template>
        </el-table-column>
        <el-table-column label="锁定库存" :width="200">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.lockStock"
              size="mini"
              placeholder="锁定库存"
            />
          </template>
        </el-table-column>
        <el-table-column label="sku编码" :width="200">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.skuCode"
              size="mini"
              placeholder="自定义sku编码"
            />
          </template>
        </el-table-column>
        <el-table-column label="价格" :width="160">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.price"
              size="mini"
              placeholder="价格,单位:分"
            />
          </template>
        </el-table-column>
        <el-table-column label="销量" :width="160">
          <template slot-scope="scope">
            <el-input v-model="scope.row.sale" size="mini" />
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" :width="160">
          <template slot-scope="scope">
            <span v-if="scope.row.id">
              <el-button
                style="color: red"
                size="mini"
                type="text"
                @click="delSku(scope.row)"
                >删除
              </el-button>
              <el-button size="mini" type="text" @click="editSkuInfo(scope.row)"
                >修改编辑
              </el-button>
            </span>
            <span v-else>
              <el-button
                style="color: red"
                size="mini"
                type="text"
                @click="delNewSku(scope.row)"
                >删除
              </el-button>
              <el-button size="mini" type="text" @click="saveNewSku(scope.row)"
                >保存
              </el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { findAllbrand } from "@/api/market";
import {
  getproductList,
  switchNewStatus,
  switchRecommandStatus,
  switchPublishStatus,
  switchVerifyStatus,
  delProduct,
  getSkusByProductId,
  addProductSkus,
  delSku,
  updateSkuInfo,
} from "@/api/product";
import mixin from "@/minx/index";
import { uuid } from "vue-uuid";
export default {
  props: {},
  mixins: [mixin],
  data() {
    return {
      searchForm: {},
      form: {
        productId: "",
        promotionPrice: "",
        promotionPerLimit: "",
        sort: "",
        promotionStartTime: "",
        promotionEndTime: "",
      },
      options: [],
      productList: [],
      skuList: [],
      open: false,
      id: "",
      sKuobj: {},
    };
  },
  computed: {},
  created() {
    this.init();
  },
  mounted() {},
  watch: {},
  methods: {
    async init() {
      this.productList = (
        await getproductList(
          this.page.currentPage,
          this.page.size,
          this.searchForm
        )
      ).data.rows;
      console.log(this.productList);
      this.page.total = (
        await getproductList(
          this.page.currentPage,
          this.page.size,
          this.searchForm
        )
      ).data.total;
      this.options = (await findAllbrand()).data.items;
    },
    // 重置表单
    regist() {
      this.searchForm = {};
      this.init();
    },
    // 搜索
    onsubmit() {
      this.init();
    },
    //修改状态
    changeStatus(key, item) {
      const id = item.id;
      // console.log(key)
      if (key === "newStatus") {
        const status = item[key];
        switchNewStatus({
          productId: id,
          status,
        }).then((res) => {
          if (res.success) {
            this.$message.success("修改状态成功");
            this.init();
          }
        });
      } else if (key === "recommendStatus") {
        const status = item[key];
        switchRecommandStatus({
          productId: id,
          status,
        }).then((res) => {
          if (res.success) {
            this.$message.success("修改状态成功");
            this.init();
          }
        });
      } else if (key === "publishStatus") {
        const status = item[key];
        switchPublishStatus({
          productId: id,
          status,
        }).then((res) => {
          if (res.success) {
            this.$message.success("修改状态成功");
            this.init();
          }
        });
      } else if (key === "verifyStatus") {
        const status = item[key];
        switchVerifyStatus({
          productId: id,
          status,
        }).then((res) => {
          if (res.success) {
            this.$message.success("修改状态成功");
            this.init();
          }
        });
      }
    },
    // 点击编辑跳转
    edit(el) {
      // console.log(el)
      this.$router.push({path:"/product/edit",query:{ids:el.id}})
    },
    editSku(el) {
      this.id = el.id;

      this.open = true;
      this.skuInit();

      //  console.log(this.skuList)
    },
    //获取skuList
    skuInit() {
      this.skuList = [];
      getSkusByProductId(this.id).then((res) => {
        if (res.success) {
          res.data.items.forEach((item) => {
            this.skuList.push({
              ...item,
              spData: JSON.parse(item.spData),
            });
          });
        }
      });
    },
    //删除商品
    delProduct(el) {
      const id = el.id;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delProduct(id).then((res) => {
            if (res.success) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.init();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //分页
    handleSizeChange(val) {
      // console.log(val);
      this.page.size = val;
      this.page.currentPage = 1;
      this.init();
    },
    handleCurrentChange(val) {
      // this.start=val
      this.page.currentPage = val;
      this.init();
    },
    //新增sku
    addSku() {
      const obj = {
        productId: this.id,
        lockStock: "",
        lowStock: "",
        stock: "",
        pic: "",
        price: "",
        sale: "",
        skuCode: "",
        spData: [
          { key: "颜色", value: "" },
          { key: "容量", value: "" },
        ],
        tempId: uuid.v1(),
      };
      this.skuList.push(obj);
      // console.log(obj);
    },
    addTiImg(res) {
      // console.log(res)
      this.skuList.forEach((el) => {
        if (el === this.sKuobj) {
          el.pic = res.data.fileUrl;
        }
      });
    },
    delSku(el) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delSku(el.id).then((res) => {
            if (res.success) {
              this.$message.success("删除成功");
              //  this.open=false
              this.skuInit();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    delNewSku(el) {
      // console.log(el)
      // const index = this.skuList.findIndex((item) => item.tempId == el.tempId);
      this.$confirm("此操作将永久删除该sku, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // this.skuList.splice(index, 1);
          this.skuList=this.skuList.filter((item)=>item.tempId!==el.tempId)
          // this.skuInit();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    editSkuInfo(el) {
      delete el.tempId;
      updateSkuInfo({
        ...el,
        spData: JSON.stringify(el.spData),
      }).then((res) => {
        if (res.success) {
          this.$message.success("修改sku成功");
          this.skuInit();
        }
      });
    },
    saveNewSku(el) {
      // console.log(el);
      delete el.tempId;
      addProductSkus({
        ...el,
        spData: JSON.stringify(el.spData),
      }).then((res) => {
        if (res.success) {
          this.$message.success("添加sku成功");
          this.skuInit();
        }
      });
    },
    saveSku(el) {
      this.sKuobj = el;
    },
    addProduct() {
      this.$router.push({ path: "/product/addDetail" });
    },
    //导出excel
    handeleExcel(){
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['商品名称', '商品品牌', '商品价格']
                const filterVal = ['name', 'brandName', 'price']
                const list = this.productList
                 const data = this.formatJson(filterVal, list)
  excel.export_json_to_excel({
    header: tHeader, //表头 必填
    data, //具体数据 必填
    filename: 'excel-list', //非必填
    autoWidth: true, //非必填
    bookType: 'xlsx' //非必填
  })
  console.log(excel)
})
    },
     formatJson(filterVal, jsonData) {
            return jsonData.map((v) =>
                filterVal.map((j) => {
                    return v[j]
                })
            )
        }
  },
  components: {},
};
</script>

<style lang="scss" scoped>
.pic {
  width: 100%;
  height: 100%;
}
.btn {
  float: right;
}
</style>
